package cn.com.miaoto.business.controller;

import cn.com.miaoto.base.common.BaseController;
import cn.com.miaoto.base.common.PageResult;
import cn.com.miaoto.base.common.PageSearch;
import cn.com.miaoto.base.common.ReturnMsg;
import cn.com.miaoto.business.model.Company;
import cn.com.miaoto.business.service.CompanyService;
import cn.com.miaoto.model.LoginUser;
import cn.com.miaoto.model.Role;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公司信息
 * Created by guo.chen on 2018/9/17.
 */
@RestController
@RequestMapping("company")
public class CompanyController extends BaseController {

    @Resource
    private CompanyService companyService;

    @GetMapping("selectPageList")
    public PageResult selectPageList(HttpSession session, PageSearch pageSearch){
        Role currentRole=(Role) session.getAttribute("currentRole");
        LoginUser loginUser =(LoginUser) session.getAttribute("currentUser");
        List<Company> companyList = null;
        try{
            Example example = new Example(Company.class);
            //注意：排序使用的是列名
            example.setOrderByClause("creator DESC,company_name  ASC");

            if(currentRole.getRoleName().equals("管理员") || currentRole.getRoleName().equals("销售主管")){
                PageHelper.startPage(pageSearch.getPage(),pageSearch.getLimit());
                companyList = this.companyService.selectByExample(example);
                return new PageResult<Company>(companyList);
            }else {
                //条件查询使用的是属性名
                example.createCriteria().andEqualTo("creator", loginUser.getUserId());
                PageHelper.startPage(pageSearch.getPage(),pageSearch.getLimit());
                companyList = this.companyService.selectByExample(example);
                return new PageResult<Company>(companyList);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("查询公司信息列表失败");
            return new PageResult();
        }
    }

    @GetMapping("selectAll")
    public List<Company> selectAll(HttpServletRequest request){
        try{
            return  this.companyService.selectAll();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("查询公司列表失败");
            return null;
        }
    }

    @GetMapping("selectByPrimaryKey")
    public ReturnMsg selectByPrimaryKey(Integer id){
        try{
            Company company = this.companyService.selectByKey(id);
            return new ReturnMsg(true,company);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("根据主键查询公司信息失败");
            return new ReturnMsg(false);
        }
    }

    @PostMapping("edit")
    public ReturnMsg insertOrUpdate(HttpSession session,@RequestBody Company company){
        LoginUser loginUser =(LoginUser) session.getAttribute("currentUser");
        try {
            if(StringUtils.isEmpty(company.getId())){
                company.setCreator(loginUser.getUserId());
                company.setCreateTime(LocalDateTime.now());
                return new ReturnMsg(this.companyService.saveNotNull(company)>0,"新增公司信息成功");
            } else
                return new ReturnMsg(this.companyService.updateNotNull(company)>0,"修改公司信息成功");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("编辑公司信息失败");
            return new ReturnMsg(false);
        }
    }

    @DeleteMapping("deleteByIds")
    public ReturnMsg deleteByIds(String ids){
        try {
            return new ReturnMsg(this.companyService.deleteAllByIds(ids)>0);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("删除公司信息失败");
            return new ReturnMsg(false);
        }
    }


    @GetMapping(value = "/downLoadExcel")
    public void downLoadExcel(HttpServletRequest request, HttpServletResponse response){
        response.reset();
        Map<String,Object> map = new HashMap<String,Object>();
        // 指定下载的文件名
        response.setHeader("Content-Disposition", "attachment;filename=custom_info.xlsx");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        XSSFWorkbook workbook=null;
        OutputStream output;
        try {
            //导出Excel对象
            workbook = companyService.exportExcel();
            output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            bufferedOutPut.flush();
            workbook.write(bufferedOutPut);
            bufferedOutPut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping(value="uploadExcel")
    public void uploadPayerCreditInfoExcel(HttpServletRequest request,HttpServletResponse response, HttpSession session){
        LoginUser loginUser =(LoginUser) session.getAttribute("currentUser");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        try {
            if (file.isEmpty()) {
                throw new Exception("文件不存在！");
            }
            InputStream in = file.getInputStream();
            companyService.uploadExcel(in, file, loginUser);
            in.close();
            PrintWriter out = null;
            response.setCharacterEncoding("utf-8");  //防止ajax接受到的中文信息乱码
            out = response.getWriter();
            out.print(JSONObject.toJSON(new ReturnMsg("0","导入Excel成功")).toString());
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
